﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;

namespace EnvironmentValueSetter
{
    class Program
    {

        static readonly string[] symbol = new string[] { "User:", "Sys:", "Path:", };

        /*
         *


         * 通常需要做的地方有:Android studio的JAVA_HOME变量         
         * 需要做path的有adb,git,jdk,nodejs
--------------------------------------------------------------------------------------------------------------
TXT例子
#用户变量(↑是分隔符)
User:JAVA_HOME↑c:\jdk1.8.0_25



#系统变量/环境变量
#例子;Sys:motherfuck↑XXXXXXX



#Path
Path:F:\Profession\Git\cmd;F:\Profession\jdk1.8.0_25\bin;C:\Program Files (x86)\nodejs\;
--------------------------------------------------------------------------------------------------------------
         */
        static void Main(string[] args)
        {
            try
            {           
            start:
                Console.WriteLine("[q]输入q退出");
                //Console.WriteLine("[2]或者输入文件名,将对环境变量进行设置");
                Console.WriteLine("[s]输入s将读取default.txt然后设置变量");
                Console.WriteLine("[d]输入d将进入清除模式");
                Console.WriteLine("不输出将进入读取模式");
                string input = Console.ReadLine();
                if (input != null && input.Equals("q", StringComparison.InvariantCultureIgnoreCase))
                    return;
                if (input.Equals("d"))
                {
                    StopwatchLog(o => Clear(o), input);
                    goto start;
                }

                if (input.Equals("s"))
                {
                    StopwatchLog(o => Set(o), input);
                    goto start;
                }
                if (string.IsNullOrEmpty(input))
                {
                    EnvironmentVariableHander.OutPutOldPath();
                    goto start;
                }
                //Console.WriteLine("不支持的命令.按任意键退出");
                Console.ReadKey();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Console.ReadKey();
            }

        }


        private static void Clear(string input)
        {
            Console.WriteLine("输出文件名,不输入将加载delete.txt");
            string temp = Console.ReadLine();
            input = string.IsNullOrEmpty(temp) ? "delete.txt" : temp;
            if (!File.Exists(input))
                return;
            Dictionary<string, string> sysDictionary = new Dictionary<string, string>();
            string s2 = symbol[1];

            Dictionary<string, string> userDictionary = new Dictionary<string, string>();
            string s1 = symbol[0];

            List<string> pathList = new List<string>();
            string s3 = symbol[2];
            using (StreamReader sr = new StreamReader(new FileStream(input, FileMode.Open, FileAccess.ReadWrite), Encoding.Default))
            {
                while (!sr.EndOfStream)
                {
                    string text = sr.ReadLine();
                    if (string.IsNullOrEmpty(text))
                        continue;
                    if (text.StartsWith("//") || text.StartsWith("#"))
                    {
                        Console.WriteLine(text);
                        continue;
                    }

                    //系统变量
                    if (text.Trim().StartsWith(s1))
                    {
                        text = text.Replace(s1, "");
                        var array = text.Split('↑');
                        if (array != null && array.Length > 0)
                        {
                            sysDictionary.Add(array[0], "");
                            continue;
                        }
                    }
                    //用户变量
                    if (text.Trim().StartsWith(s2))
                    {
                        text = text.Replace(s2, "");
                        var array = text.Split('↑');
                        if (array != null && array.Length > 0)
                        {
                            userDictionary.Add(array[0], "");
                            continue;
                        }
                    }
                    //Path,特殊处理
                    if (text.StartsWith(s3))
                    {

                        var shit = text.Replace(s3, "").Split(';');
                        for (int i = 0; i < shit.Length; i++)
                        {
                            pathList.Add(shit[i]);
                        }
                    }
                }
                Console.WriteLine("即将开始装逼请不要关闭窗体");
                var machineValueSetter = new EnvironmentVariableHander(EnvironmentVariableTarget.Machine);
                if (pathList.Count > 0)
                {
                    machineValueSetter.ClearPath(pathList);
                }
                if (userDictionary.Count > 0)
                {
                    machineValueSetter.Set(userDictionary);
                    //foreach (var item in userDictionary)
                    //{
                    //    Console.WriteLine(item.Key + ":" + item.Value);
                    //}
                }
                if (sysDictionary.Count > 0)
                {
                    new EnvironmentVariableHander(EnvironmentVariableTarget.User).Set(sysDictionary);
                    //foreach (var item in sysDictionary)
                    //{
                    //    Console.WriteLine(item.Key + ":" + item.Value);
                    //}
                }
            }
        }

        private static void StopwatchLog(Action<string> action, string input)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            action(input);
            sw.Stop();
            Console.WriteLine("执行完毕.耗时{0}秒", sw.ElapsedMilliseconds);
        }

        private static void Set(string input)
        {
            Console.WriteLine("输入文件名,不输入将加载default.txt");
            string temp = Console.ReadLine();
            input = string.IsNullOrEmpty(temp) ? "default.txt" : temp;
            if (!File.Exists(input))
                return;
            //获取path路径数组集合
            //获取用户变量字典集合
            using (StreamReader sr = new StreamReader(new FileStream(input, FileMode.Open, FileAccess.ReadWrite), Encoding.Default))
            {
                Dictionary<string, string> sysDictionary = new Dictionary<string, string>();
                string s2 = symbol[1];

                Dictionary<string, string> userDictionary = new Dictionary<string, string>();
                string s1 = symbol[0];

                List<string> pathList = new List<string>();
                string s3 = symbol[2];
                while (!sr.EndOfStream)
                {
                    string text = sr.ReadLine();
                    if (string.IsNullOrEmpty(text))
                        continue;
                    if (text.StartsWith("//") || text.StartsWith("#"))
                    {
                        Console.WriteLine(text);
                        continue;
                    }
                    //系统变量
                    if (text.Trim().StartsWith(s1))
                    {
                        text = text.Replace(s1, "");
                        var array = text.Split('↑');
                        if (array != null && array.Length == 2)
                        {
                            sysDictionary.Add(array[0], array[1]);
                            continue;
                        }
                    }
                    //用户变量
                    if (text.Trim().StartsWith(s2))
                    {
                        text = text.Replace(s2, "");
                        var array = text.Split('↑');
                        if (array != null && array.Length == 2)
                        {
                            userDictionary.Add(array[0], array[1]);
                            continue;
                        }
                    }
                    //Path,特殊处理
                    if (text.StartsWith(s3))
                    {
                        var shit = text.Replace(s3, "").Split(';');
                        for (int i = 0; i < shit.Length; i++)
                        {
                            pathList.Add(shit[i]);
                        }
                    }
                }
                Console.WriteLine("即将开始装逼请不要关闭窗体");
                var machineValueSetter = new EnvironmentVariableHander(EnvironmentVariableTarget.Machine);
                EnvironmentVariableHander.OutPutOldPath();
                if (pathList.Count > 0)
                {
                    machineValueSetter.SetPath(pathList);
                }
                if (userDictionary.Count > 0)
                {
                    machineValueSetter.Set(userDictionary);
                    //foreach (var item in userDictionary)
                    //{
                    //    Console.WriteLine(item.Key + ":" + item.Value);
                    //}
                }
                if (sysDictionary.Count > 0)
                {
                    new EnvironmentVariableHander(EnvironmentVariableTarget.User).Set(sysDictionary);
                    //foreach (var item in sysDictionary)
                    //{
                    //    Console.WriteLine(item.Key + ":" + item.Value);
                    //}
                }
            }
        }
    }
}
